package com.example.partner.activity;

import static com.example.partner.common.ConfigConstant.BASE_URL;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.alibaba.fastjson.JSON;
import com.example.partner.common.BaseResponse;
import com.example.partner.databinding.ActivityChatBinding;
import com.example.partner.model.domain.Im;
import com.example.partner.adapter.ChatAdapter;
import com.example.partner.service.ImService;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;
import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.WebSocket;
import okhttp3.WebSocketListener;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class ChatActivity extends AppCompatActivity {
    final String TAG = "ChatActivity";
    private ActivityChatBinding binding;
    private List<Im> ims;
    private ChatAdapter chatAdapter;
    private ImService imService;
    String username,avatar;
    Long userid, toid;
    private WebSocket mSocket;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding=ActivityChatBinding.inflate(getLayoutInflater());
        //getLayoutInflater()从当前Activity中获取一个LayoutInflater,用于将XML布局文件转换为视图
        // 这里使用activity_chat布局文件来为当前活动创建一个新的视图，并返回一个与该布局绑定的ActivityChatBinding对象
        setContentView(binding.getRoot());//将当前活动的界面设置为与布局文件中的根视图对应的视图。
        SharedPreferences sharedPreferences = getSharedPreferences("CurrentUser", MODE_PRIVATE);
        userid=sharedPreferences.getLong("userId",-1);
        // 初始化
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        imService = retrofit.create(ImService.class);
        loadReceiverDetails();//接收要联系的对象的信息
        init();
        //开启连接
        start(userid);
        setListeners();//图标的监听事件
    }
    /**
     * 刷新view
     * */
    private void updateRecyclerView(){
        //当有新消息时，刷新RecyclerView中的显示
        chatAdapter.notifyItemInserted(ims.size() - 1);
        //将RecyclerView定位到最后一行
        binding.chatRecyclerView.scrollToPosition(ims.size() - 1);
    }

    /**
     * 开启web socket连接
     * */
    private void start(Long userId) {

        OkHttpClient mOkHttpClient = new OkHttpClient.Builder()
                .readTimeout(300, TimeUnit.SECONDS)//设置读取超时时间
                .writeTimeout(300, TimeUnit.SECONDS)//设置写的超时时间
                .connectTimeout(300, TimeUnit.SECONDS)//设置连接超时时间
                .build();

        //定义request
        Request request = new Request.Builder().url(BASE_URL+"/api/test/"+userId).build();
        //绑定回调接口
        mOkHttpClient.newWebSocket(request, new EchoWebSocketListener());
        mOkHttpClient.dispatcher().executorService().shutdown();

    }

    /**
     * 显示内容
     * */
    private void output(final Im im) {
        runOnUiThread(() -> {
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");
            SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd  HH:mm:ss");
            try {
                Date date=format.parse(im.getCreateTime());
                String time = format1.format(date);
                im.setCreateTime(time);
            } catch (ParseException e) {
                throw new RuntimeException(e);
            }
            ims.add(im);
            updateRecyclerView();
        });
    }


    /**
     * 内部类，监听web socket回调
     * */
    private final class EchoWebSocketListener extends WebSocketListener {
        @Override
        public void onMessage(WebSocket webSocket, String text) {
            super.onMessage(webSocket, text);
            Im im = JSON.parseObject(text, Im.class);
            output(im);
        }
        @Override
        public void onOpen(WebSocket webSocket, okhttp3.Response response) {
            super.onOpen(webSocket, response);
            mSocket = webSocket;    //实例化web socket
        }
        @Override
        public void onClosed(WebSocket webSocket, int code, String reason) {
            super.onClosed(webSocket, code, reason);
        }
        @Override
        public void onFailure(WebSocket webSocket, Throwable t, okhttp3.Response response) {
            super.onFailure(webSocket, t, response);
        }
    }

    private void init(){
        ims=new ArrayList<>();
        chatAdapter=new ChatAdapter(
                ims,avatar,userid,ChatActivity.this
        );
        binding.chatRecyclerView.setAdapter(chatAdapter);
//        根据发送者和接收者的id从后端获取历史聊天记录，在初始化的时候展示出来
        imService.findAllInit(userid,toid).enqueue(new Callback<BaseResponse<List<Im>>>() {
            @Override
            public void onResponse(Call<BaseResponse<List<Im>>> call, Response<BaseResponse<List<Im>>> response) {
                if (response.isSuccessful() && response.body() != null) {
                    if(response.body().getData()!=null) {
                        List<Im> ims1 = response.body().getData();
                        for (Im im : ims1) {
                            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");
                            SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd  HH:mm:ss");
                            try {
                                Date date=format.parse(im.getCreateTime());
                                String time = format1.format(date);
                                im.setCreateTime(time);
                            } catch (ParseException e) {
                                throw new RuntimeException(e);
                            }
                            ims.add(im);//把历史记录逐一加入列表里面
                        }
                        updateRecyclerView();
                        binding.chatRecyclerView.setVisibility(View.VISIBLE);
                        binding.progressBar.setVisibility(View.GONE);
                    }
                }
            }
            @Override
            public void onFailure(Call<BaseResponse<List<Im>>> call, Throwable t) {
                // 网络错误处理
                t.printStackTrace();
            }
        });
    }
    private void sendMessage(){//点击发送按钮发送消息
        String content = binding.inputMessage.getText().toString();
        if (!"".equals(content)) {
            Im im = new Im();
            im.setText(content);
            im.setUid(userid);
            im.setToId(toid);
            im.setUsername("to-"+username);
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");
            format.setTimeZone(TimeZone.getTimeZone("GMT+8"));
            String createTime = format.format(new Date());
            im.setCreateTime(createTime);
            mSocket.send(JSON.toJSONString(im));
            //调用后端接口把发送的消息保存到数据库里，表示发送成功
            imService.save(im).enqueue(new Callback<BaseResponse<Boolean>>() {
                @Override
                public void onResponse(Call<BaseResponse<Boolean>> call, Response<BaseResponse<Boolean>> response) {
                    BaseResponse<Boolean> responseBody = response.body();
                    String message = responseBody.message;
                    if (response.isSuccessful()) {
                    } else {
                        Toast.makeText(ChatActivity.this,message,Toast.LENGTH_SHORT).show();
                        // 处理错误情况
                    }
                }
                @Override
                public void onFailure(Call<BaseResponse<Boolean>> call, Throwable t) {
                    // 网络错误处理
                    Log.e(TAG, "post回调失败：" + t.getMessage() + "," + t.toString());
                    Toast.makeText(ChatActivity.this, t.getMessage()+"post回调失败", Toast.LENGTH_SHORT).show();
                }
            });
            SimpleDateFormat format2 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");
            SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd  HH:mm:ss");
            try {
                Date date=format2.parse(im.getCreateTime());
                String time = format1.format(date);
                im.setCreateTime(time);
            } catch (ParseException e) {
                throw new RuntimeException(e);
            }
            ims.add(im);
            updateRecyclerView();//刷新RecyclerView
            binding.inputMessage.setText(null);//发送完消息把输入框清空
        }
    }


    private void loadReceiverDetails(){//从上一个activity接收要联系的对象的信息
        Intent intent =getIntent();
        toid=intent.getLongExtra("toid",0);
        username = intent.getStringExtra("username");
        avatar=intent.getStringExtra("avatar");
        binding.textName.setText(username);
    }

    private  void setListeners(){
        binding.imageBack.setOnClickListener(view -> onBackPressed());//返回图标的监听事件
        binding.layoutSend.setOnClickListener(view -> sendMessage());//发送消息图标的监听事件
    }

}